import React, { useState, useEffect } from 'react';
import { saveAs } from 'file-saver';
import './index.css'

function base64toFile(dataURI: any, suffix: any) {
  const byteString = atob(dataURI.split(',')[1]);
  // 获取文件类型
  const ab = new ArrayBuffer(byteString.length);
  const ia = new Uint8Array(ab);
  for (let i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ab], { type: `image/${suffix}` });
}

export default () => {
  const [images, setImages] = useState<any>('');
  const [text, setText] = useState<any>('');

  useEffect(() => {
  }, []);

  const upFile1 = (d: any) => {
    const files = d.target.files;
    console.log('files===', files);
    const len = files.length;
    setImages(files);
    for (let i = 0; i < len; i++) {
      var fr = new FileReader();
      fr.onload = function (e) {
        console.log("回显了图片")
        let img = document.createElement("img");
        img.src = e.target?.result;
        img.width = 200;
        img.height = 200;
        document.getElementById("images")?.appendChild(img);
      }
      fr.readAsDataURL(files[i]);//读取文件
    }
    if(text){
      toGen(files, text);
    }
  };

  const onAddText = (d: any) => {
    console.log('文本内容===', d.target?.value);
    const text = d.target?.value;
    if (!text) {
      return;
    }
    const infoList = text?.split("\n");
    if (!infoList?.length) {
      return;
    }
    setText(text);
    if (!!images?.length) {
      toGen(images, text);
    }
  };

  const toGen = (imgs: any, textStr: any) => {
    const infoList = textStr?.split("\n");
    // 时间
    const timeStr = infoList[3];
    const timeObj = new Date(timeStr.substring(3));
    let hours = timeObj.getHours();
    let minutes = timeObj.getMinutes();

    for (let i = 0; i < imgs?.length; i++) {
      const reader = new FileReader();
      const file = imgs[i];
      reader.readAsDataURL(file);
      reader.onload = (e: any) => {
        const img = new Image();
        img.src = e.target.result;
        img.onload = () => {
          // const canvas = document.getElementById('myCanvas' + i) as HTMLCanvasElement;
          let canvas = document.createElement("canvas");
          canvas.setAttribute("id", "myCanvas"+i);
          document.getElementById("canvasList")?.appendChild(canvas);
          if (canvas?.getContext('2d')) {
            const ctx = canvas.getContext('2d');
            canvas.width = img.width;
            canvas.height = img.height;
            ctx?.clearRect(0, 0, canvas.width, canvas.height);
            ctx?.drawImage(img, 0, 0, canvas.width, canvas.height);
            ctx.font = `bold 20px arial`;
            ctx.fillStyle = 'grey';
            ctx.textAlign = "left";
            ctx.textBaseline = 'bottom';
            for (let j = 0; j < infoList.length; j++) {
              console.log('txt====', infoList[j]);
              // 时间需要处理
              console.log("j===", j);
              
              if(j===3){
              const randomSeconds = Math.floor(Math.random() * (60 - 10) + 10); // 随机生成大于10的秒数
              let randomMinutes = minutes + Math.floor(Math.random() * (6 - 2) + 2); // 递增2-5秒
              if(randomMinutes > 59){
                randomMinutes = 0;
                hours =  hours+1;
              }
              minutes = randomMinutes;
              console.log("hours===", hours);
              console.log("randomMinutes===", randomMinutes);
              console.log("randomSeconds===", randomSeconds);
              timeObj.setHours(hours, randomMinutes, randomSeconds);
              console.log(timeObj);
              const timeTxt = timeStr.substring(0, 3) + timeObj.toLocaleString().replace("/", "-");
              ctx?.fillText(timeTxt, 50, canvas.height - 40*(infoList.length-j+1));
              }else{
                ctx?.fillText(infoList[j], 50, canvas.height - 40*(infoList.length-j+1));
              }
            }
          }
        };
      };
    }
  }

  const downloadFile = () => {
    const canvasDiv = document.getElementById("canvasList");
    const canvas = canvasDiv?.getElementsByTagName('canvas');
    for(let i=0;i<canvas?.length;i++){
      const imageName = images[i].name;
      const suffixStr = imageName.substring(imageName.lastIndexOf(".") + 1);
      const base64Data = canvas[i].toDataURL(`image/${suffixStr}`);
      const blob = base64toFile(base64Data, suffixStr);
      saveAs(blob, imageName);
    }
    
  };

  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
        alignContent: 'center',
        backgroundColor: '#f5f5f5',
      }}
    >
      <div
        style={{
          marginTop: '20px',
          display: 'flex',
          alignContent: 'center',
          alignItems: 'center',
          textAlign: 'center',
        }}
      >
        <div style={{ margin: 10, padding: 5 }}>
          <div
            style={{
              display: 'flex',
              alignContent: 'center',
              alignItems: 'center',
            }}
          >
            <div style={{}}>
              <label
                style={{
                  textAlign: 'center',
                  margin: '10px 0px',
                  padding: '10px',
                  backgroundColor: '#fff',
                  borderRadius: '25px',
                }}
              >
                上传主图
                <input
                  type="file"
                  multiple
                  accept="image/*"
                  onChange={(d) => upFile1(d)}
                  style={{ display: 'none' }}
                />
              </label>
            </div>
          </div>
        </div>
        <button
          style={{
            margin: '10px 0px',
            fontSize: '24px',
            borderRadius: '20px',
            backgroundColor: "lightgreen"
          }}
          onClick={() => downloadFile()}
          disabled={!images?.length || !text}
        >
          点击下载
        </button>
      </div>
      <div
        style={{
          marginTop: '20px',
          display: 'flex',
          alignContent: 'center',
          alignItems: 'center',
          textAlign: 'center',
        }}
      >
        <label
          style={{
            textAlign: 'center',
            margin: '10px',
            padding: '10px',
          }}
        >
          输入文案
        </label>
        <textarea rows={8} cols={60} onChange={(d) => onAddText(d)} />
      </div>
      <div
        id="images"
        style={{
          backgroundColor: 'white',
          border: '0.5px solid',
          margin: 20,
        }}
      >

      </div>
      <div
        id="canvasList"
        style={{
          backgroundColor: 'white',
          border: '0.5px solid',
          margin: 20,
        }}
      >

      </div>
    </div>
  );
};
